﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace Ebusiness_UserService.Services.UnitOfWork
{
    public class UnitOfWorkFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // ✅ 方法执行前
            //Console.WriteLine("Before action executes");
            // 执行下一个中间件（实际调用控制器方法）
            var result = await next();
            // ✅ 方法执行后
            //Console.WriteLine("After action executes");
            if (result.Exception != null) //只有action 执行成功，才会自动调用savechanges
                return;
            var actionDec = context.ActionDescriptor as ControllerActionDescriptor;
            if (actionDec == null)
                return;
            var uowAttr = actionDec.MethodInfo.GetCustomAttribute<UnitOfWorkAttribute>();
            if (uowAttr == null)
                return;
            foreach (var item in uowAttr.DbContextTypes)
            {
                var contexts = context.HttpContext.RequestServices.GetService(item) as DbContext;
                //提交事务
                if (contexts != null)
                    await contexts.SaveChangesAsync();
                
            }
        }
    }
}
